<template>
  <el-card shadow="hover" :body-style="{ padding: '20px' }">
    <el-badge class="item" :value="tmObj.records.length">
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTradeMark"
        v-visite="'btn.Trademark.add'"
        >添加</el-button
      >
    </el-badge>

    <el-switch v-model="st" />

    <el-table
      border
      style="margin: 10px 0px"
      :data="tmObj.records"
      v-loading="loading"
      element-loading-text="正在加载中..."
      element-loading-background="rgba(122.122.122.0.2)"
    >
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="品牌名称"
        align="center"
        prop="tmName"
      ></el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template #="{ row, $index }">
          <a :title="row.tmName">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 60px; border-radius: 10px"
            />
          </a>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="updateTradeMark(row)"
          ></el-button>

          <el-popconfirm
            :title="`确定删除${row.tmName}?`"
            width="250px"
            :icon="Delete"
            @confirm="handler(row)"
          >
            <template #reference>
              <el-button type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="tmObj.total"
      :page-sizes="[3, 5, 7]"
      background
      :pager-count="7"
      layout="prev, pager, next, jumper,->,sizes,total"
      @size-change="sizeHandler"
      @current-change="getTradeMarkList"
    >
    </el-pagination>

    <el-dialog
      v-model="dialogFormVisible"
      :title="tmParams.id ? '添加品牌' : '添加品牌'"
      draggable
    >
      <el-form
        style="width: 80%"
        label-width="90px"
        :model="tmParams"
        :rules="rules"
        ref="formRef"
      >
        <!--收集品牌名称-->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="tmParams.tmName" />
        </el-form-item>
        <!--收集品牌lOGO-->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tmParams.logoUrl"
              :src="tmParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
//引入上传图片成功人家需要的类型
import type { UploadProps, FormInstance, FormRules } from "element-plus";

import { ElMessage, ElNotification } from "element-plus";

//引入请求函数
import {
  reqTradeMarkList,
  reqAddOrUpdateTradeMark,
  reqDeleteTradeMark,
} from "../../../api/product/trademark/trademark";

import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";

import type {
  trademarkResponseData,
  trademark,
} from "../../../api/product/trademark/model/trademark";

import { useUserInfoStore } from "../../../stores/userInfo";
//获取仓库
let userInfoStore = useUserInfoStore();

//分页器当前第几页
let currentPage = ref<number>(1);
//当前页显示几条数据
let pageSize = ref<number>(3);

let loading = ref<boolean>(false);

let formRef = ref<FormInstance>();

let dialogFormVisible = ref<boolean>(false);
let st = ref<boolean>(false);
let tmParams = reactive<trademark>({
  tmName: "",
  logoUrl: "",
});

let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});

//挂载
onMounted(() => {
  getTradeMarkList();
});

const getTradeMarkList = async (page: number = 1) => {
  loading.value = true;
  currentPage.value = page;
  let result = await reqTradeMarkList(currentPage.value, pageSize.value);
  tmObj.total = result.total;
  tmObj.records = result.records;
  loading.value = false;
};

const sizeHandler = (limit: number) => {
  pageSize.value = limit;
  getTradeMarkList();
};
//上传图片成功钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data;
};

//上传图片成功之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 <= 50) {
      return true;
    }
  } else {
    return false;
  }
};

const addOrUpdate = async () => {
  formRef.value.validate(async (success) => {
    if (success) {
      await reqAddOrUpdateTradeMark(tmParams);
      dialogFormVisible.value = false;
      getTradeMarkList(tmParams.id ? currentPage.value : 1);

      ElMessage({
        type: "success",
        message: tmParams.id ? "修改品牌成功" : "添加品牌成功",
      });
    } else {
      ElNotification({
        type: "warning",
        message: "注意规则",
        duration: 500,
      });
    }
  });
};

//确定按钮的回调
const addTradeMark = () => {
  dialogFormVisible.value = true;
  tmParams.tmName = "";
  tmParams.logoUrl = "";
  tmParams.id = "";
  nextTick(() => {
    formRef.value.resetFields();
  });
};

const updateTradeMark = (row: trademark) => {
  dialogFormVisible.value = true;

  nextTick(() => {
    formRef.value.resetFields();
    tmParams.id = row.id;
    tmParams.tmName = row.tmName;
    tmParams.logoUrl = row.logoUrl;
  });
};

//自定义校验规则
const validatetmName = (rule: any, value: any, next: any) => {
  if (value.length > 2) {
    next();
  } else {
    next(new Error("品牌名大于2"));
  }
};

//表单验证规则
const rules = reactive<FormRules>({
  tmName: [{ required: true, trigger: "blur", validator: validatetmName }],
  logoUrl: [{ required: true, message: "上传logo图片" }],
});

const handler = async (row: trademark) => {
  try {
    await reqDeleteTradeMark(row.id);
    ElMessage({
      type: "success",
      message: `删除${row.tmName}成功`,
    });
    getTradeMarkList(currentPage.value);
  } catch (error) {}
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

>>> span {
  color: skyblue;
}
>>> li.is-active {
  background: green !important;
}
</style>
  
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>